

//
//  HTEmoticonKeyBoardViewModel.swift
//  weibo
//
//  Created by JonsonLiu on 16/4/27.
//  Copyright © 2016年 liujonson. All rights reserved.
//

import UIKit

class HTEmoticonKeyBoardViewModel: NSObject {
    
    
    static let sharedViewModel : HTEmoticonKeyBoardViewModel = HTEmoticonKeyBoardViewModel()

    lazy var emotionBundle : NSBundle = {

        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        return NSBundle(path: path)!
    }()
    
     lazy var defaultEmoticons : [HTEmoticon] = {
    
        return self.emoticonWithPath("default/info.plist")
        
           }()
    
     lazy var emojEmoticons: [HTEmoticon] = {
    
        return self.emoticonWithPath("emoji/info.plist")
    }()
    
     lazy var lxhEmoticons: [HTEmoticon] = {
    
        return self.emoticonWithPath("lxh/info.plist")
    }()
    
     lazy var allEmotcions : [[[HTEmoticon]]] = {
    
        return [
            [[HTEmoticon]()],
            self.emoticonPageArray(self.defaultEmoticons),
            self.emoticonPageArray(self.emojEmoticons),
            self.emoticonPageArray(self.lxhEmoticons),
        ]
    }()
 
    
    /// 把108个数组 分割成6页,每一页最多20个
    ///
    /// - parameter filePath: <#filePath description#>
    ///
    /// - returns: <#return value description#>
    private func emoticonPageArray(emoticon : [HTEmoticon]) -> [[HTEmoticon]] {
    
        let  pageCount = (emoticon .count - 1) / 20 + 1
        var result : [[HTEmoticon]] = [[HTEmoticon]]()
        
        for i  in 0..<pageCount {
        
            let loc = 20 * i
            var len = 20
            
            if loc + len > emoticon.count{
            
                len = emoticon.count - loc
            }
            
            let childArray = (emoticon as NSArray).subarrayWithRange(NSMakeRange(loc, len)) as! [HTEmoticon]
            
            result.append(childArray)

        }
        return result
    }
    
    
    
    /// 抽取获取文件的路径
    ///
    /// - parameter filePath: <#filePath description#>
    ///
    /// - returns: <#return value description#>
    private func emoticonWithPath(filePath : String) -> [HTEmoticon]{
    
        
        // 1. 取到默认表情的info.plist路径
        let path = self.emotionBundle.pathForResource(filePath, ofType: nil)!
        
        // 2. 读取字典数组
        let dicts = NSArray(contentsOfFile: path)!
        
        // 3. 初始化一个模型数组以保存模型
        var tempArray = [HTEmoticon]()
        
        // 4. 字典转模型
        for value in dicts {
            let model = HTEmoticon(dict: (value as! [String : AnyObject]))
            
            let folderName = (filePath as NSString).stringByDeletingLastPathComponent
            model.folderName = folderName
            
            tempArray.append(model)
        }
        
        // 5. 返回
        return tempArray

        
    }
    
}
